

package com.hazelcast.internal.monitor.impl;

import com.hazelcast.internal.metrics.Probe;
import com.hazelcast.internal.monitor.LocalFlakeIdGeneratorStats;
import com.hazelcast.internal.util.Clock;

import java.util.concurrent.atomic.AtomicLongFieldUpdater;

import static com.hazelcast.internal.metrics.MetricDescriptorConstants.*;
import static com.hazelcast.internal.metrics.ProbeUnit.MS;
import static java.util.concurrent.atomic.AtomicLongFieldUpdater.newUpdater;

public class LocalFlakeIdGeneratorStatsImpl implements LocalFlakeIdGeneratorStats {

    private static final AtomicLongFieldUpdater<LocalFlakeIdGeneratorStatsImpl> BATCH_COUNT = newUpdater(LocalFlakeIdGeneratorStatsImpl.class, "batchCount");
    private static final AtomicLongFieldUpdater<LocalFlakeIdGeneratorStatsImpl> ID_COUNT = newUpdater(LocalFlakeIdGeneratorStatsImpl.class, "idCount");

    @Probe(name = FLAKE_ID_METRIC_CREATION_TIME, unit = MS)
    private final long creationTime;
    @Probe(name = FLAKE_ID_METRIC_BATCH_COUNT)
    private volatile long batchCount;
    @Probe(name = FLAKE_ID_METRIC_ID_COUNT)
    private volatile long idCount;

    public LocalFlakeIdGeneratorStatsImpl() {
        creationTime = Clock.currentTimeMillis();
    }

    @Override
    public long getCreationTime() {
        return creationTime;
    }

    @Override
    public long getBatchCount() {
        return batchCount;
    }

    @Override
    public long getIdCount() {
        return idCount;
    }

    public void update(int batchSize) {
        BATCH_COUNT.incrementAndGet(this);
        ID_COUNT.addAndGet(this, batchSize);
    }

    @Override
    public String toString() {
        return "LocalFlakeIdStatsImpl{" + "creationTime=" + creationTime + ", batchCount=" + batchCount + ", idCount=" + idCount + '}';
    }
}
